package com.ja.openchat.ui.chat.group;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemLongClickListener;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.chat.group.adapter.GroupSendListAdapter;
import com.ja.openchat.ui.chat.group.adapter.GroupSendModule;
import com.ja.openchat.ui.contact.ContactChooseActivity;
import com.ja.openchat.views.ChatUserDialog;
import com.ja.openchat.views.ChooseListDialog;
import com.ja.openchat.views.ContactGroupSendDialog;
import com.ja.openchat.views.OnChooseListListener;
import com.lxj.xpopup.XPopup;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.model.group.GroupSendInfo;
import com.zy.openchat.core.model.group.LocalMessageInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

//新建群发
public class GroupSendActivity extends JaBaseActivity {

    @BindView(R.id.rv_group_send_msg)
    RecyclerView rvGroupSendMsg;
    @BindView(R.id.tv_create_group_send)
    TextView tvCreateGroupSend;

    public static final int REQUEST_CODE_FOR_GROUP_SEND = 8888;

    private GroupSendListAdapter groupSendListAdapter;

    public static void start(Context activity) {
        Intent intent = new Intent();
        intent.setClass(activity, GroupSendActivity.class);
        activity.startActivity(intent);
    }


    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_group_send;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
    public List<String> chooseLables = Arrays.asList(new String[]{App.getInstanse().getString(R.string.delete_text)});
    @Override
    public void initView() {
        super.initView();
        setTitle(getString(R.string.group_assistant));

        tvCreateGroupSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                ContactChooseActivity.startWithCreateGroupSend(GroupSendActivity.this,REQUEST_CODE_FOR_GROUP_SEND);
                sendMessage();
            }
        });

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvGroupSendMsg.setLayoutManager(layoutManager);
        groupSendListAdapter = new GroupSendListAdapter();
        rvGroupSendMsg.setAdapter(groupSendListAdapter);
        groupSendListAdapter.setEmptyView(R.layout.status_center_qunfa_empty_view);
        groupSendListAdapter.getEmptyLayout().findViewById(R.id.ll_send).setOnClickListener(v -> {
            //新建群发
//            ContactChooseActivity.startWithCreateGroupSend(GroupSendActivity.this,REQUEST_CODE_FOR_GROUP_SEND);

            sendMessage();
        });
        groupSendListAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                GroupSendInfo groupSendInfo = groupSendListAdapter.getItem(position);
                if(!groupSendInfo.isEmpty()){
                    ChatActivity.startActivity(GroupSendActivity.this,groupSendInfo, REQUEST_CODE_FOR_GROUP_SEND);
                }

            }
        });
        groupSendListAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                final GroupSendInfo groupSendInfo = groupSendListAdapter.getItem(position);
                ChooseListDialog.showChooseListDialog(GroupSendActivity.this, chooseLables, -1, new OnChooseListListener() {
                    @Override
                    public void onChoose(int position, String value) {
                        GroupSendManager.getInstance().removeGroupSendInfo(groupSendInfo);
                        groupSendListAdapter.notifyDataSetChanged();
                        if(groupSendListAdapter.getData().size() == 0){
                            tvCreateGroupSend.setVisibility(View.GONE);
                        }else {
                            tvCreateGroupSend.setVisibility(View.VISIBLE);
                        }
                    }
                });
                return true;
            }
        });
        rvGroupSendMsg.post(new Runnable() {
            @Override
            public void run() {
                groupSendListAdapter.setNewInstance(GroupSendManager.getInstance().getGroupSendInfos());
                if(groupSendListAdapter.getData().size() == 0){
                    tvCreateGroupSend.setVisibility(View.GONE);
                }else {
                    tvCreateGroupSend.setVisibility(View.VISIBLE);
                }
            }
        });
    }




    private void doGroupSend(final GroupSendInfo sendInfo,final LocalMessageInfo messageInfo){
        if(sendInfo==null||sendInfo.isEmpty()||messageInfo==null){
            return;
        }
        showProgress();

        final GroupSendModule sendModule = new GroupSendModule(this,sendInfo.userIds,messageInfo);
        if(mProgressDialog!=null){
            mProgressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    sendModule.onDestory();
                }
            });
        }
        sendModule
                .sendMessage()
                .subscribe(new Observer<List<Observable<TgResponse>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(List<Observable<TgResponse>> observables) {
                        Observable.merge(observables)
                                .subscribe(new Observer<TgResponse>() {
                                    @Override
                                    public void onSubscribe(Disposable d) {

                                    }

                                    @Override
                                    public void onNext(TgResponse tgResponse) {

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        showErrorTip(e.getMessage());
                                    }

                                    @Override
                                    public void onComplete() {
                                        sendModule.onDestory();
                                        hideProgress();
                                        sendInfo.messageInfo = messageInfo;
                                        GroupSendManager.getInstance().appendGroupSendInfo(sendInfo);
                                        groupSendListAdapter.notifyDataSetChanged();
                                        if(groupSendListAdapter.getData().size() == 0){
                                            tvCreateGroupSend.setVisibility(View.GONE);
                                        }else {
                                            tvCreateGroupSend.setVisibility(View.VISIBLE);
                                        }

                                        rvGroupSendMsg.post(new Runnable() {
                                            @Override
                                            public void run() {
                                                rvGroupSendMsg.scrollToPosition(groupSendListAdapter.getData().size()-1);
                                            }
                                        });
                                    }
                                });
                    }

                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        showErrorTip(e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Override
    public void onTgEvent(TgEvent tg_event) {
        switch (tg_event.event){
            case EUser_Td_Chat_Send_Message_Success:
            case EUser_Td_Chat_Send_Message_Fail:
                if(tg_event.data!=null&&tg_event.data instanceof MessageInfo&&tg_event.dataEx instanceof Long){
                    MessageInfo messageInfo = (MessageInfo)tg_event.data;

                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_CODE_FOR_GROUP_SEND){
            if(data!=null&&data.getSerializableExtra("message")!=null&&data.getSerializableExtra("groupsend")!=null){
                LocalMessageInfo messageInfo = (LocalMessageInfo) data.getSerializableExtra("message");
                GroupSendInfo groupSendInfo = (GroupSendInfo) data.getSerializableExtra("groupsend");
                doGroupSend(groupSendInfo,messageInfo);
            }
        }
    }

    private void sendMessage(){
        new XPopup.Builder(this)
                .hasShadowBg(true)
                .isDestroyOnDismiss(true)
                .dismissOnTouchOutside(true)
                .moveUpToKeyboard(false)
                .autoOpenSoftInput(false)
                .borderRadius(10)
                .atView(binding.getRoot())
                .asCustom(new ContactGroupSendDialog(this,ContactChooseActivity.ContactChooseType.ContactChooseType_CreateGroupSend, new ContactGroupSendDialog.OnItemClickListner() {

                    @Override
                    public void clickPostion(LocalMessageInfo messageInfo, GroupSendInfo groupSendInfo) {
                        if(messageInfo!=null&&groupSendInfo!=null){
                            doGroupSend(groupSendInfo,messageInfo);
                        }
                    }
                })).show();
    }


}
